﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoboBrowse.Api;
using BoboBrowse.Facets;
using BoboBrowse.Facets.impl;
using Lucene.Net.Analysis;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
using WebApp1.Models;
using NewsMine.DomainObjects;
using NewsDiscoveryEngine.Index;

namespace WebApp1.AdminSection
{
    public partial class BoboBrowser : System.Web.UI.Page
    {
        #region Keyword related stuff

        private void BindCategoriesToDropDownListBox(bool refresh = false)
        {
            //cmbCategoryName.DataTextField = ".";
            if (refresh == true || cmbCategoryName.Items == null || cmbCategoryName.Items.Count == 0)
            {
                List<string> keyWordCategories = NewsMine.DataManagers.KeyWordManager.GetAllCategories();

                cmbCategoryName.DataSource = keyWordCategories;
                cmbCategoryName.DataBind();

                cmbCategoryName.SelectedIndex = -1;
            }
        }

        protected void btnGetKeyWords_Click(object sender, EventArgs e)
        {
            if (cmbCategoryName.SelectedIndex > -1)
            {
                string selectedCategory = cmbCategoryName.SelectedValue.ToString();

                SelectCategory(selectedCategory);
            }
        }

        protected void cmbCategoryName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCategoryName.SelectedIndex > -1)
            {
                string selectedCategory = cmbCategoryName.SelectedValue.ToString();

                SelectCategory(selectedCategory);
            }
        }

        private void SelectCategory(string category)
        {
            string selectedCategory = category;

            lblSelectedCategory.Text = cmbCategoryName.SelectedValue;

            cmbCategoryName.SelectedValue = category;

            var keywords = NewsMine.DataManagers.KeyWordManager.GetAllKeywordsByCategory(selectedCategory);

            string query = "titlelink:" + String.Join(" OR titlelink:", keywords);

            txtSearchBox.Text = query;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

            if (SecurityCheckManager.IsAdminPortalEabled() == false)
            {
                Response.Write("You should be the admin....");
                return;
            }

            BindCategoriesToDropDownListBox();

            string searchText = txtSearchBox.Text;

            string fieldName = txtFieldName.Text;

            if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(fieldName))
            {
                Response.Write("you need to provide proper query and search text.");

                return;
            }

            string globalFilter = txtGlobalFilter.Text;

            if (string.IsNullOrEmpty(globalFilter))
            {
                globalFilter = "*:*";
            }

            string finalSearchQueryAlongWithContextQuery ="( " + searchText + ") AND " + globalFilter;

            int maxRecsPerpage = 0;

            try
            {
                maxRecsPerpage = Convert.ToInt32(txtMaxRecords.Text);
            }
            catch (Exception exx)
            {
                if (maxRecsPerpage == 0)
                    maxRecsPerpage = 500;
            }


            int maxCountGlobal = 0;
            int maxCount = 0;

            int universalMaxCount = 0;

            FacetReader facetReader = new FacetReader();

            var facetsUniversal = facetReader.GetFacets("*:*", fieldName, out universalMaxCount);

            var facetsGlobal = facetReader.GetFacets(globalFilter, fieldName, out maxCountGlobal);
            Response.Write("Total number of documents in the index : " + maxCountGlobal.ToString() + "<br/>");

            var facets = facetReader.GetFacets(finalSearchQueryAlongWithContextQuery, fieldName, out maxCount);

            Response.Write("Total number of documents in the index : " + maxCount.ToString() + "<br/>");

            double totalPercentOfFilteredDocs = maxCount * 100 / maxCountGlobal;

            Response.Write("Filtered Docs percentage in Global view : " + totalPercentOfFilteredDocs.ToString() + "<br/>");

            int precesion = 100;


            List<KeyWordTokenDensity> densityInfoList = new List<KeyWordTokenDensity>();

            foreach (var item in facets)
            {
                densityInfoList.Add(
                    new KeyWordTokenDensity
                    {
                        TokenName = item.Key,
                        TokenCount = Convert.ToDouble(item.Value),
                        TokenCountPercentage = Convert.ToDouble((item.Value * precesion / maxCount)),
                        ContextualTokenCount = Convert.ToDouble(facetsGlobal[item.Key]),
                        ContextualTokenPercentage = Convert.ToDouble((item.Value * precesion / facetsGlobal[item.Key])),
                        TokenUniversalCount = Convert.ToDouble(facetsUniversal[item.Key]),
                        TokenUniversalPercentage = Convert.ToDouble((item.Value * precesion / facetsUniversal[item.Key]))
                    }
                    );
            }

         //  densityInfoList = facetReader.GetKeyWordDensityCloud(searchText, fieldName);

            

            //densityInfoList = (from item in densityInfoList
            //                   where item.TokenCount > 1 && item.TokenGlobalPercentage >= totalPercentOfFilteredDocs
            //                   orderby item.TokenUniversalPercentage * item.TokenCountPercentage descending, item.TokenUniversalPercentage descending , 
            //                   item.TokenUniversalCount descending, item.TokenGlobalPercentage descending , 
            //                   item.TokenGlobalCount descending, item.TokenCountPercentage descending,   
            //                   (item.TokenCountPercentage - 5) * item.TokenGlobalPercentage descending 
            //                   select item).ToList();

            densityInfoList = (from item in densityInfoList
                               where item.TokenCount > 1 && item.ContextualTokenPercentage >= totalPercentOfFilteredDocs
                               orderby 
                               item.TokenUniversalPercentage * item.TokenCountPercentage descending,
                               item.TokenUniversalPercentage descending, 
                               item.TokenUniversalCount descending, item.ContextualTokenPercentage descending,
                               item.ContextualTokenCount descending, item.TokenCountPercentage descending,
                               (item.TokenCountPercentage - 5) * item.ContextualTokenPercentage descending
                               select item).ToList();


            Response.Write("<table>");
            Response.Write("<tr><th></th><th>Token Name</th><th></th><th>Count</th><th>Global Count</th><th>Universal Count</th><th> Relative %</th><th>Global %</th><th>Universal %</th><th>Score</th> </tr>");

            int count = 0;

            string selectedCategory = string.Empty;
            string stopWordCategory = "stopwords";
            if (cmbCategoryName.SelectedIndex != -1)
            {
                selectedCategory = cmbCategoryName.SelectedValue;
            }

            if (selectedCategory.ToLower() == stopWordCategory)
            {
                selectedCategory = string.Empty;
            }

            var alreadySelectedClassifiedKeywordsAlongWithStopWords = new List<string>();

            if (!string.IsNullOrEmpty(selectedCategory))
            {
                alreadySelectedClassifiedKeywordsAlongWithStopWords = NewsMine.DataManagers.KeyWordManager.GetAllKeywordsByCategory(selectedCategory);
            }

            alreadySelectedClassifiedKeywordsAlongWithStopWords.AddRange(NewsMine.DataManagers.KeyWordManager.GetAllKeywordsByCategory(stopWordCategory));

            alreadySelectedClassifiedKeywordsAlongWithStopWords = alreadySelectedClassifiedKeywordsAlongWithStopWords.Distinct().ToList();



            foreach (var item in densityInfoList)
            {
                if (count >= maxRecsPerpage)
                    break;

                if (item.TokenUniversalPercentage * item.TokenCountPercentage > 0)
                {
                    Response.Write("<tr style='background-color:#fff9f9;'>");
                }
                else
                {
                    Response.Write("<tr>");
                }
               

                Response.Write("<td>");
                Response.Write((++count).ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.TokenName);
                Response.Write("</td>");


                Response.Write("<td>");

                if (alreadySelectedClassifiedKeywordsAlongWithStopWords.Contains(item.TokenName.ToLower()))
                {
                    Response.Write("Selected...");
                }
                else
                {
                    Response.Write("<a kw=\"" + item.TokenName.ToLower() + "\" class=\"catact btn btn-warning\">" + stopWordCategory + "</a>");

                    if (!string.IsNullOrEmpty(selectedCategory))
                    {
                        Response.Write("<a kw=\"" + item.TokenName.ToLower() + "\"  class=\"catact btn\">" + selectedCategory + "</a>");
                    }
                }

                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.TokenCount.ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.ContextualTokenCount.ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.TokenUniversalCount.ToString());
                Response.Write("</td>");

                Response.Write("<td>");
                Response.Write(item.TokenCountPercentage.ToString());
                Response.Write(" %</td>");
                Response.Write("<td>");
                Response.Write(item.ContextualTokenPercentage.ToString());
                Response.Write(" %</td>");

                Response.Write("<td>");
                Response.Write(item.TokenUniversalPercentage.ToString());
                Response.Write(" %</td>");

                   Response.Write("<td>");
                   Response.Write((item.TokenUniversalPercentage * item.TokenCountPercentage).ToString());
                Response.Write(" points</td>");
              
                

            

                Response.Write("</tr>");

            }
            Response.Write("</table>");



         


        }


       

        #region commented old code Page_load with all bobobrowser display

       


        #endregion
    }
}